<!--
 * @file 轨迹查看组件
 * @description 基于百度地图Track API的轨迹查看组件(简化版)
 * @date 2024-08-21 (更新)
 * @reference https://lbsyun.baidu.com/index.php?title=jspopular3.0/guide/polyline
 -->
<template>
  <div class="track-viewer">
    <!-- 地图容器 -->
    <MapContainer 
      ref="mapRef"
      :center="mapCenter"
      :zoom="mapZoom"
      :map-type="mapType"
      @ready="handleMapReady"
    />
    
    <!-- 轨迹控制器 - 使用提取的TrackPlayer组件 -->
    <TrackPlayer
      v-if="trackLoaded"
      :track-loaded="trackLoaded"
      :current-time="formattedCurrentTime"
      :formatted-distance="formattedDistance"
      :is-playing="isPlaying"
      @play="handlePlayTrack(mapRef)"
      @pause="handlePauseTrack(mapRef)"
      @seek="handleSeek"
      @speed-change="handleSpeedChange"
      @range-change="handleRangeChange"
      @toggle-range="handleToggleRange"
    />
    
    <!-- 加载状态 -->
    <div v-if="loading" class="track-loading">
      <div class="track-loading__spinner"></div>
      <div class="track-loading__text">加载轨迹数据中...</div>
    </div>
    
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
import MapContainer from '@/components/monitor/map/MapContainer.vue';
import { useMapStore } from '@/stores/modules/map';
import { logger } from '@/utils/system/logger';
import { useTrackViewer } from '@/hooks/monitor/useTrackViewer';
import TrackPlayer from '@/components/monitor/track-player/TrackPlayer.vue';

// 导入类型定义
import type { TrackQueryParams } from '@/types/track';

// 组件属性
const props = defineProps({
  deviceId: {
    type: String,
    required: true
  },
  startTime: {
    type: String,
    required: true
  },
  endTime: {
    type: String,
    required: true
  },
  autoPlay: {
    type: Boolean,
    default: false
  },
  mapCenter: {
    type: Object,
    default: () => ({ lng: 116.404, lat: 39.915 })
  },
  mapZoom: {
    type: Number,
    default: 15
  },
  mapType: {
    type: String,
    default: 'normal'
  }
});

// 组件事件
const emit = defineEmits<{
  (e: 'track-loaded', data: { pointsCount: number; distance: number }): void;
  (e: 'track-start'): void;
  (e: 'track-pause'): void;
  (e: 'track-resume'): void;
  (e: 'track-stop'): void;
  (e: 'track-error', error: string | Error): void;
}>();

// 响应式状态
const mapRef = ref<any>(null);
const track = ref<any>(null);        // Track.View 实例
const isPlaying = ref(false);        // 是否正在播放
const currentSpeed = ref('1');       // 当前速度
const currentPlayTime = ref('00:00');
const currentProgress = ref(0);      // 添加当前播放进度百分比

// 使用地图store
const mapStore = useMapStore();

// 使用轨迹查看器hook - 使用合并后的API
const { 
  trackLoaded,
  loading,
  trackPointsCount,
  totalDistance,
  formattedDistance,
  // 轨迹动画控制
  startAnimation,
  pauseAnimation,
  resumeAnimation,
  stopAnimation,
  // 使用新增的轨迹播放控制方法
  handlePlayTrack,
  handlePauseTrack,
  handleResetTrack,
  // 轨迹处理
  trackLine,
  fetchTrackData,
  drawTrack,
  clearTrackView,
  handleTrackError
} = useTrackViewer({ autoPlay: props.autoPlay });

/**
 * 加载轨迹插件
 */
async function loadTrackPlugin(): Promise<boolean> {
  if (!window.Track) {
    const success = await mapStore.loadTrackPlugin();
    if (!success) {
      handleTrackError('轨迹插件加载失败，请刷新页面重试', null, {});
      return false;
    }
  }
  
  return !!window.Track;
}

/**
 * 处理地图准备好事件
 */
async function handleMapReady(event: any): Promise<void> {
  logger.info('地图已准备好', { component: 'TrackViewer' });
  const map = event.map;
  
  // 确保轨迹插件已加载
  if (!mapStore.isTrackReady || !window.Track) {
    // 尝试加载轨迹插件
    if (!await loadTrackPlugin()) return;
  }
  
  try {
    // 创建轨迹图层
    track.value = new window.Track.View(map, {
      lineLayerOptions: {
        style: {
          strokeWeight: 8,
          strokeLineJoin: 'round',
          strokeLineCap: 'round'
        }
      }
    });
    
    // 加载轨迹数据
    await loadTrackData();
  } catch (err) {
    handleTrackError('创建轨迹图层失败', err, {});
  }
}

/**
 * 加载轨迹数据
 */
async function loadTrackData(): Promise<void> {
  const queryParams: TrackQueryParams = {
    deviceId: props.deviceId,
    startTime: props.startTime,
    endTime: props.endTime
  };
  
  // 使用hook提取的方法获取数据
  const result = await fetchTrackData(queryParams);
  
  if (result) {
    // 绘制轨迹
    await drawTrack(result.trackPointsData, track.value, mapRef);
    
    // 发送事件
    emit('track-loaded', {
      pointsCount: trackPointsCount.value,
      distance: totalDistance.value
    });
    
    // 如果设置了自动播放，则开始播放
    if (props.autoPlay) {
      handlePlayTrack(mapRef);
      isPlaying.value = true;
    }
  }
}

/**
 * 处理进度变化
 */
function handleSeek(percentage: number): void {
  console.log('设置播放进度:', percentage);
  
  // 更新当前进度
  currentProgress.value = percentage;
  
  // 根据百分比计算当前时间并更新
  currentPlayTime.value = formatTimeFromPercentage(percentage);
  
  // 如果轨迹实例存在，调用百度地图轨迹API进行跳转
  if (track.value && trackLine.value) {
    const totalPoints = trackLine.value.getNumPoints();
    if (totalPoints > 0) {
      const pointIndex = Math.floor((percentage / 100) * totalPoints);
      track.value.seekAndUpdate(pointIndex);
    }
  }
}

/**
 * 根据百分比格式化时间
 */
function formatTimeFromPercentage(percentage: number): string {
  // 假设一天24小时
  const totalMinutes = 24 * 60;
  const minutes = Math.floor((percentage / 100) * totalMinutes);
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
}

/**
 * 处理播放速度变化
 */
function handleSpeedChange(speed: number): void {
  console.log('设置播放速度:', speed);
  currentSpeed.value = String(speed);
  // 实现改变播放速度的逻辑
  // 这里需要调用百度地图轨迹API的相关方法
}

/**
 * 处理时间范围变化
 */
function handleRangeChange(startPercentage: number, endPercentage: number): void {
  console.log('设置时间范围:', startPercentage, endPercentage);
  // 实现时间范围变化的逻辑
  // 根据百分比计算实际的开始和结束时间
}

/**
 * 处理显示范围开关切换
 */
function handleToggleRange(show: boolean): void {
  console.log('切换显示范围:', show);
  // 实现显示/隐藏范围的逻辑
}

// 当前时间计算
const formattedCurrentTime = computed(() => {
  return currentPlayTime.value;
});

/**
 * 更新轨迹播放进度
 */
function updateTrackProgress() {
  if (trackLine.value && track.value && isPlaying.value) {
    try {
      // 获取当前播放进度
      const currentIndex = trackLine.value.getCurrentPointIndex();
      const totalPoints = trackLine.value.getNumPoints();
      
      if (totalPoints > 0) {
        // 计算百分比
        const percentage = (currentIndex / totalPoints) * 100;
        currentProgress.value = percentage;
        
        // 更新时间显示
        currentPlayTime.value = formatTimeFromPercentage(percentage);
      }
    } catch (err) {
      logger.error('更新轨迹进度失败', err);
    }
  }
}

// 添加轨迹状态变更事件监听
watch(() => trackLine.value, (newTrackLine: any) => {
  if (newTrackLine) {
    // 监听轨迹状态变化事件
    newTrackLine.on(window.Track?.LineCodes?.STATUS, (status: number) => {
      switch(status) {
        case window.Track?.StatusCodes?.PLAY:
          emit('track-start');
          isPlaying.value = true;
          // 开始定时更新进度
          startProgressTimer();
          break;
        case window.Track?.StatusCodes?.PAUSE:
          emit('track-pause');
          isPlaying.value = false;
          // 停止定时更新进度
          stopProgressTimer();
          break;
        case window.Track?.StatusCodes?.RESUME:
          emit('track-resume');
          isPlaying.value = true;
          // 重新开始定时更新进度
          startProgressTimer();
          break;
        case window.Track?.StatusCodes?.STOP:
        case window.Track?.StatusCodes?.FINISH:
          emit('track-stop');
          isPlaying.value = false;
          // 停止定时更新进度
          stopProgressTimer();
          break;
      }
    });

    // 监听轨迹播放进度，百度地图API中可能有类似PROCESS的事件
    // 但如果没有现成的事件，我们可以使用定时器定期检查和更新进度
    if (window.Track?.LineCodes?.PROCESS) {
      newTrackLine.on(window.Track.LineCodes.PROCESS, () => {
        updateTrackProgress();
      });
    }
  }
}, { immediate: false });

// 定时器引用
let progressTimer: number | null = null;

/**
 * 启动进度更新定时器
 */
function startProgressTimer() {
  // 清除可能存在的旧定时器
  stopProgressTimer();
  
  // 创建新的定时器，每100毫秒更新一次进度
  progressTimer = window.setInterval(() => {
    updateTrackProgress();
  }, 100);
}

/**
 * 停止进度更新定时器
 */
function stopProgressTimer() {
  if (progressTimer !== null) {
    window.clearInterval(progressTimer);
    progressTimer = null;
  }
}

// 监听属性变化
watch(
  () => [props.deviceId, props.startTime, props.endTime],
  () => {
    logger.info('轨迹查询参数变化，重新加载轨迹', {
      component: 'TrackViewer',
      deviceId: props.deviceId,
      startTime: props.startTime,
      endTime: props.endTime
    });
    
    // 清除现有轨迹
    clearTrackView();
    
    // 重新获取轨迹数据
    if (track.value) {
      loadTrackData();
    }
  },
  { deep: true }
);

// 组件挂载
onMounted(() => {
  // 记录组件挂载日志
  logger.info('轨迹查看组件已挂载', { component: 'TrackViewer' });
  // 地图组件加载完成后会触发handleMapReady事件，在那里初始化轨迹
});

// 组件卸载时清理资源
onUnmounted(() => {
  // 停止进度更新定时器
  stopProgressTimer();
});

// 暴露组件方法
defineExpose({
  loadTrackData,
  startAnimation,
  pauseAnimation,
  resumeAnimation,
  stopAnimation,
  handlePlayTrack,
  handlePauseTrack,
  handleResetTrack,
  clearTrackView
});
</script>

<style lang="scss">
.track-viewer {
  position: relative;
  width: 100%;
  height: 100%;
  
  /* 加载状态样式 */
  .track-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(255, 255, 255, 0.9);
    padding: 16px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    z-index: 20;
    
    &__spinner {
      width: 30px;
      height: 30px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #3498db;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    &__text {
      font-size: 14px;
      color: #333;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 